<?php
/**
 * Created by PhpStorm.
 * Author: Shadow
 * Date: 2022/5/28
 * Time: 9:23 上午
 * description: GoodsBusiness.php
 */

namespace app\api\business;
use app\api\model\Sku;
use app\api\model\Spu;
use think\db\exception\PDOException;
use think\facade\Db;

/**
 * 商品业务逻辑类
 * Class GoodsBusiness
 */
class GoodsBusiness
{

    /**
     * 添加商品
     */
    public static function addGoods($param){

        # 添加商品 spu、sku

        // 启动事务
        Db::startTrans();
        try {
            $param['goods_logo'] = \think\facade\Filesystem::disk('public')->putFile( 'image', $param['goods_logo']);
            $spuData = [
                'goods_name'    => $param['goods_name'],
                'goods_logo'    => $param['goods_logo'],
                'category_id'   => $param['category_level_3'],
                'brand_id'      => $param['brand_id'],
                'goods_attr'    => json_encode($param['attr'],JSON_UNESCAPED_UNICODE),
                'goods_detail'  => $param['goods_detail'],
                'create_time'   => time(),

            ];

            $spuResult = Spu::create($spuData);
            $spu_id = $spuResult->id;

            $skuData = [
                'spu_id'        => $spu_id,
                'spec_info'     => $param['spec_info'],
                'price'         => $param['price'],
                'market_price'  => $param['market_price'],
                'cost_price'    => $param['cost_price'],
            ];
            $skuResult = Sku::create($skuData);
            // 提交事务
            Db::commit();
            return true;
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            abort($e->getCode(),$e->getMessage());
        }
    }

}